package com.jieshuibao.controller;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.po.BaseRes;
import com.jieshuibao.model.db.Tvbox;
import com.jieshuibao.service.TvboxService;
import com.jieshuibao.util.DateUtils;
import com.jieshuibao.util.StringUtils;

@Controller
@RequestMapping(value = "/tv")
public class TvBoxController {
	private static final Logger log  = Logger.getLogger(TvBoxController.class);
	
	@Resource
	private TvboxService tvboxService;
	
	@RequestMapping(value = "/tvbox", method = RequestMethod.POST)
	@ResponseBody
	public Object list(HttpServletRequest request){
		BaseRes<Object> res = new BaseRes<Object>();
		String userid = request.getHeader("cookieId");
		if(StringUtils.isEmpty(userid)){
			res.setCode("0");
			res.setDes("系统繁忙!");
			return res;
		}
		Tvbox tvboxByDeviceNo = tvboxService.getTvboxByDeviceNo(userid);
		if(null == tvboxByDeviceNo){
			res.setCode("0");
			res.setDes("没有权限观看!");
			log.error("该设备编号:"+userid+"不在白名单内");
			return res;
		}
		Date createDate = tvboxByDeviceNo.getCreateDate();
		Date now = new Date();
		if(null != createDate){
			if(now.before(createDate)){
				res.setCode("1");
				res.setDes("启动成功!");
				return res;
			}else{
				res.setCode("0");
				res.setDes("该盒子已经过期失效!");
				log.error("该盒子:"+userid+"已经过期失效");
				return res;
			}
		}
		Tvbox tvbox = new Tvbox();
		tvbox.setDeviceNo(userid);
		tvbox.setCreateDate(DateUtils.addYears(now, 1));//过期时间  默认首次使用一年后过期
		tvboxService.updateTvbox(tvbox);
		res.setCode("1");
		res.setDes("启动成功!");
		return res;
	}
}
